<template>
  <el-row class="register-now">
    <el-col :span="24">
      <p class="header-style">
        注册
      </p>
    </el-col>
    <el-form ref="formRegister"
             :model="formRegister"
             label-width="80px"
             :rules="rules">
      <el-col :span="24">
        <el-form-item label="用户名"
                      prop="user_no">
          <el-input v-model="formRegister.user_no"
                    @keyup.native="judgeUserName"
                    placeholder="请输入用户名"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item label="姓名"
                      prop="user_name">
          <el-input v-model="formRegister.user_name"
                    placeholder="请输入姓名"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item label="密码"
                      prop="password">
          <el-input v-model="formRegister.password"
                    type="password"
                    placeholder="请输入密码"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item label="确认密码"
                      prop="confirm_password">
          <el-input v-model="formRegister.confirm_password"
                    type="password"
                    placeholder="请输入确认密码"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item label="手机号"
                      prop="phone">
          <el-input v-model="formRegister.phone"
                    type="text"
                    placeholder="请输入手机号"
                    maxlength="11"
                    @input="onInput"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item label="验证码"
                      prop="code">
          <!-- <input v-model="formRegister.code"
                 type="text"
                 placeholder="请输入验证码"
                 @input="onInputCode" />
          <el-button @click="getRegisterVerifyCode"
                     class="get-verify-btn"
                     :disabled="verifyCodeDisabled"
                     :class="{ disabled: verifyCodeDisabled }"
                     type="primary">{{ verifyCodeBtnText }}</el-button> -->
          <el-input placeholder="请输入验证码"
                    v-model="formRegister.code"
                    class="input-with-select">
            <el-button slot="append"
                       @click="getRegisterVerifyCode"
                       :disabled="verifyCodeDisabled"
                       :class="{ disabled: verifyCodeDisabled }"> {{ verifyCodeBtnText }}</el-button>
          </el-input>
        </el-form-item>
      </el-col>
      <el-col :span="24"
              class="bottom-box">
        <el-button type="primary"
                   @click="getKey('formRegister')">注册</el-button>
        <el-button type="text"
                   @click="toggleLoginOrRegister('passwordLogin')"
                   class="now-register">已有账号,立即登录</el-button>
      </el-col>
    </el-form>
  </el-row>
</template>

<script>
import { userPermissionApi } from "@/services/UserPermission";
var checkPwd = (rule, value, cb) => {
  //验证密码的正则表达式
  const regPwd =
    /^(?=.*[0-9].*)(?=.*[A-Z].*)(?=.*[a-z].*)(?=.*[`~!@#$%^&*()_\-+=<>.?:"{}].*).{10,32}$/
  if (regPwd.test(value)) {
    return cb()
  }
  cb(new Error('密码需包含大小写字母、数字及特殊字符，长度在10-32位之间'))
}
export default {
  props: {
    onRegisterFunc: Function,
    user_type: Number
  },
  data () {
    // 验证手机 
    let checkPhone = (rule, value, callback) => {
      let reg = /^1[345789]\d{9}$/
      if (!reg.test(value)) {
        callback(new Error('请输入11位手机号'))
      } else {
        callback()
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.formRegister.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    };
    let validPassword = (rule, value, callback) => {
      let reg = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,15}$/
      if (!reg.test(value)) {
        callback(new Error('密码必须是由6-15位字母+数字组合'))
      } else {
        callback()
      }
    };
    return { // 验证码按钮文字
      verifyCodeBtnText: "获取验证码",
      verifyCodeDisabled: false,
      formRegister: {
        user_no: '',
        user_name: '',
        password: '',
        confirm_password: '',
        code: '',
        phone: ''
      },
      rules: {
        user_no: [
          { required: true, message: '用户名不能为空', trigger: 'blur' },
          // { validator: validUserNo, trigger: 'blur' }
          // { pattern: /^[1][2,3,4,5,6,7,8,9][0-9]{9}$/, message: '用户名只能输入英文或数字' }
          { pattern: /[a-zA-Z0-9]/, message: '用户名只能输入英文或数字' }
        ],
        user_name: [
          { required: true, message: '姓名不能为空', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '密码不能为空', trigger: 'change' },
          { validator: checkPwd, trigger: 'change' }
        ],
        confirm_password: [
          { required: true, validator: validatePass2, trigger: 'change' },
          { min: 6, max: 20, message: '长度在6到20个字符', trigger: 'change' }
        ],
        code: [
          { required: true, message: '验证码不能为空', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { min: 11, max: 11, message: '请输入11位有效手机号号码', trigger: ['blur', 'change'] }
        ],
      },
      verifyCodeTimeout: 60,
      // 验证码倒计时定时器id
      verifyCodeTimeoutId: 0
    }
  },
  methods: {
    judgeUserName () {
      this.formRegister.user_no = this.formRegister.user_no.replace(/[\W]/g, '');
    },
    // 切换登录或注册状态
    toggleLoginOrRegister (mode) {
      this.verifyCodeTimeout = 60;
      this.verifyCodeDisabled = false;
      this.verifyCodeBtnText = "获取验证码";
      clearInterval(this.verifyCodeTimeoutId);
      this.status = mode;
      this.onRegisterFunc(this.status, 'hasAccount', '', '');//回调
    },

    // 根据系统编号和授权码获取key
    getKey (data1) {
      let authCode = process.env.AUTH_CODE;
      userPermissionApi
        .getKey({
          data: {
            system_no: "industry",
            auth_code: authCode
          }
        })
        .then(
          res => {
            console.log(res, "get key");
            let data = res.data;
            if (data.key) {
              window.sessionStorage.setItem("platformKey", data.key);
              this.onRegistFun(data1);
            }
          },
          err => {
            console.log(err);
          }
        );
    },
    //注册
    onRegistFun (data) {
      this.$refs[data].validate(valid => {
        if (valid) {
          userPermissionApi
            .scanRegister({
              data: {
                confirm_password: this.formRegister.confirm_password,
                password: this.formRegister.password,
                phone: this.formRegister.phone,
                user_no: this.formRegister.user_no,
                user_name: this.formRegister.user_name,
                code: this.formRegister.code,
                usage_code: 2,
                system_no: "industry",
                audit_status: 2,
                // user_type: this.user_type,
                // company_id: ''
              }
            })
            .then(
              res => {
                if (res.code === 0) {
                  this.onRegisterFunc('passwordLogin', 'noneAccount', this.formRegister.user_no, this.formRegister.password);//没有帐号
                  this.$message.success("注册成功");
                  this.formRegister = this.$options.data().formRegister;
                }
              },
              err => {
                console.log(err);
              }
            );
        }
      });
    },
    onInput () {
      this.$refs.formRegister.validateField("phone", phoneError => {
        console.log(`${phoneError}***************************`);

        if (!phoneError) {
        }
      });
    },
    // 获取注册验证码
    getRegisterVerifyCode () {
      if (this.formRegister.phone === "") {
        this.$message("手机号不能为空");
      } else {
        if (this.formRegister.phone && this.formRegister.phone.trim() !== "") {
          if (this.formRegister.phone.length !== 11) {
            this.$message("手机号长度不符合要求（11位）");
          } else {
            userPermissionApi
              .sendCode({
                data: {
                  phone: this.formRegister.phone,
                  usage_code: 2,
                  template_no: "industry-0001",
                  system_no: "industry",
                  user_type: this.user_type // 注册用户类型（3：单位管理员，4：普通用户）
                }
              })
              .then(
                res => {
                  if (res.code === 0) {
                    this.verifyCodeDisabled = true;
                    this.verifyCodeInterval();
                  }
                  console.log(res, "send login code");
                },
                err => {
                  console.log(err);
                }
              );
          }
        } else {
          this.$message.error("请输入有效手机号");
        }
      }
    },
    // 开始倒计时
    verifyCodeInterval () {
      let timeout = setInterval(() => {
        if (this.verifyCodeTimeout === 1) {
          this.verifyCodeTimeout = 60;
          this.verifyCodeDisabled = false;
          this.verifyCodeBtnText = "获取验证码";
          clearInterval(this.verifyCodeTimeoutId);
        } else {
          this.verifyCodeTimeout--;
          this.verifyCodeBtnText = "重新发送 " + this.verifyCodeTimeout;
        }
      }, 1000);
      this.verifyCodeTimeoutId = timeout;
    },
    onInputCode () {
      this.$refs.registerForm.validateField("code", codeError => {
        console.log(`${codeError}***************************`);

        if (!codeError) {
        }
      });
    },
  },
  created () {
    console.log('子组件user_type=', this.user_type)
  }
}
</script>

<style lang="scss" scoped>
.bottom-box {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
.header-style {
  font-size: 18px;
  color: #000;
  text-align: left;
  font-weight: normal;
  margin-bottom: 20px;
}
.register-now {
  padding: 20px;
}
</style>